package com.polaris.live.utils

import com.polaris.live.cache.CommonCache
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil

/**
 * DmaUtils
 *
 * @author Created by lucas on 2024/2/19 03:36
 */
object DmaUtils {

    /**
     * 欧盟国家iso 3166-1代码
     */
    val EEA = arrayOf(
        "BE", "ES", "HU", "SK",
        "BG", "FR", "MT", "FI",
        "CZ", "HR", "NL", "SE",
        "DK", "IT", "AT", "DE",
        "CY", "PL", "IS", "EE",
        "LV", "PT", "LI", "IE",
        "LT", "RO", "NO", "EL",
        "LU", "SI", "GB"
    )

    /**
     * 通过本地判断是否为eea
     */
    fun isCurrentEEA(): Boolean {
        val networkIsoCountry = AppModule.getNetworkIsoCountry()
        if (networkIsoCountry != null && isEEA(networkIsoCountry)) {
            return true
        }
        val simIsoCountry = AppModule.getSimIsoCountry()
        if (simIsoCountry != null && isEEA(simIsoCountry)) {
            return true
        }

        return isEEA(AppModule.getLanguageCountry())
    }

    /**
     * 是否为欧盟的国家（英国也包含）
     */
    fun isEEA(countryIso: String): Boolean {
        return EEA.contains(countryIso.uppercase())
    }

    /**
     * 是否需要隐私政策
     */
    fun hasPrivacy(): Boolean {
        val ipEea = CommonCache.getIpCountry()?.let { isEEA(it) }
        return ipEea == true || (ipEea == null && isCurrentEEA())
    }

    /**
     * 当前是否包含了其中一个国家
     */
    fun currentContainsCountry(countries: Set<String>): Boolean {
        val networkIsoCountry = AppModule.getNetworkIsoCountry()
        val simIsoCountry = AppModule.getSimIsoCountry()
        val appCountry = AppModule.getLanguageCountry()
        val ipCountry = CommonCache.getIpCountry()

        return countries.any {
            if (networkIsoCountry != null) {
                it == networkIsoCountry
            } else if (simIsoCountry != null) {
                it == simIsoCountry
            } else if (ipCountry != null) {
                it == ipCountry
            } else {
                it == appCountry
            }
        }
    }

    @Volatile
    private var dmaSelected: Boolean? = null

    /**
     * 获取dma选项
     */
    fun getDmaSelected(): Boolean? {
        return dmaSelected ?: let {
            CacheUtil.getDmaUserSelected().apply {
                dmaSelected = this
            }
        }
    }

    /**
     * 设置dma选项
     */
    fun setDmaUserSelected(selected: Boolean) {
        dmaSelected = selected
        CacheUtil.saveDmaUserSelected(selected)
    }

    /**
     * 设置显示过dma弹窗
     */
    fun showedDmaDialog() {
        CacheUtil.saveDmaDialogShowed()
    }

    /**
     * 获取是否显示过dma弹窗
     */
    fun isDmaDialogShowed(): Boolean {
        return CacheUtil.getDmaDialogShowed() ?: false
    }
}